﻿
using Xacml.Core.Interfaces;
using System.Collections;

namespace Xacml.Core.Runtime
{
  public class RuleCombiningAlgorithmFirstApplicable : IRuleCombiningAlgorithm
  {
    public Decision Evaluate(EvaluationContext context, RuleCollection rules)
    {
      Decision decision = Decision.Indeterminate;
      context.Trace("Evaluating rules...");
      context.AddIndent();
      try
      {
        foreach (Rule rule in (CollectionBase) rules)
        {
          decision = rule.Evaluate(context);
          context.TraceContextValues();
          if (decision == Decision.Deny)
          {
            decision = Decision.Deny;
            return decision;
          }
          if (decision == Decision.Permit)
          {
            decision = Decision.Permit;
            return decision;
          }
          if (decision != Decision.NotApplicable && decision == Decision.Indeterminate)
          {
            decision = Decision.Indeterminate;
            return decision;
          }
        }
        return Decision.NotApplicable;
      }
      finally
      {
        context.Trace("Rule combination algorithm: {0}", (object) decision.ToString());
        context.RemoveIndent();
      }
    }
  }
}
